package com.domain.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    //token过期时间
    private static final long TIME = 6000 * 60 * 1000;

    //token
    private static final String TOKEN_SECRET = "b843b06c9d014e35bb93a4a9186e4998";


    /**
     * 签名加密
     */
    public static String sign(String userPhone, String usersId) throws UnsupportedEncodingException {
        //过期时间
        Date date = new Date(System.currentTimeMillis() + TIME);
        //加密
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

        Map<String, Object> map = new HashMap<>();
        map.put("typ", "JWT");
        map.put("alg", "HS256");
        return JWT.create().withHeader(map).
                withClaim("usersId", usersId).
                withClaim("phoneNumber", userPhone).
                withExpiresAt(date).sign(algorithm);
    }


    //token是否正确
    public static boolean veryfiy(String token) throws IllegalArgumentException, UnsupportedEncodingException {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            // boolean b= veryfiy("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZU51bWJlciI6IjEzMjMyMjk3MzMyIiwidXNlcnNJZCI6IjIzMjMyMzIzMjMyMzIzMjMyMzIiLCJleHAiOjE1NDM4OTEwNjh9.rJ8jqYeVTOtm1BL1xQiZm_5q7AKwZeaqOsrNAouD2x0");
            String token = sign("13232297332", "2323232323232323232");
            System.out.println(token);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

